/*  
 * i-OSGi - Tunable Bundle Isolation for OSGi
 * Copyright (C) 2011  Sven Schulz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.iosgi.impl;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Provides;
import org.iosgi.IsolationConstraint;
import org.iosgi.IsolationConstraintRegistry;

/**
 * @author Sven Schulz
 */
@Component(immediate = true)
@Provides(specifications = IsolationConstraintRegistry.class)
public class IsolationConstraintRegistryImpl implements
		IsolationConstraintRegistry {

	private Map<String, Set<IsolationConstraint>> constraints;

	public IsolationConstraintRegistryImpl() {
		constraints = new HashMap<String, Set<IsolationConstraint>>();
	}

	private Set<IsolationConstraint> getOrCreateConstraintSet(String location) {
		Set<IsolationConstraint> c = constraints.get(location);
		if (c == null) {
			constraints.put(location, c = new HashSet<IsolationConstraint>());
		}
		return c;
	}

	@Override
	public synchronized void add(IsolationConstraint c) {
		for (String location : c.getBundles()) {
			Set<IsolationConstraint> cs = this
					.getOrCreateConstraintSet(location);
			cs.add(c);
		}
	}

	@Override
	public synchronized void remove(IsolationConstraint c) {
		for (String location : c.getBundles()) {
			Set<IsolationConstraint> cs = this
					.getOrCreateConstraintSet(location);
			cs.remove(c);
		}
	}

	@Override
	public synchronized Set<IsolationConstraint> getConstraints(String location) {
		return new HashSet<IsolationConstraint>(
				this.getOrCreateConstraintSet(location));
	}

	@Override
	public synchronized int getIsolationLevel(String a, String b) {
		int minLvl = Integer.MAX_VALUE;
		if (!a.equals(b)) {
			for (IsolationConstraint c : this.getOrCreateConstraintSet(a)) {
				String[] locations = c.getBundles();
				if (locations[0].equals(b) || locations[1].equals(b)) {
					minLvl = Math.min(minLvl, c.getLevel());
				}
			}
		}
		return minLvl;
	}

}